package com.minelx.table.core;

import com.minelx.table.core.series.Series;

import java.util.ArrayList;
import java.util.List;

public class Intersections {

	private final List<Intersection> intersections;

	private final Table left;

	private final Table right;

	public Intersections(Table left, Table right, String leftOn, String rightOn) {
		this.left = left;
		this.right = right;
		Series<String> firstColumn = left.column(leftOn);
		Series<String> secondColumn = right.column(rightOn);

		intersections = new ArrayList<>();

		firstColumn.indexes().stream()
				.forEach(index -> {
					long[] inners = secondColumn.indexesOf(firstColumn.at(index));
					for (long inner : inners) {
						intersections.add(new Intersection(index, inner));
					}
				});
	}

	public Series<String> leftRowAt(long at) {
		return left.form().row(at(at).left());
	}

	public Series<String> rightRowAt(long at) {
		return right.form().row(at(at).right());
	}

	Intersection at(long index) {
		return intersections.get((int) index);
	}

	public long length() {
		return intersections.size();
	}
}
